package com.example.mongodb.config;

import org.apache.naming.factory.BeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoConfig {

    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory factory, MongoMappingContext mongoMappingContext){
        DefaultDbRefResolver defaultDbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(defaultDbRefResolver, mongoMappingContext);
        //自定义类型转换器
        mappingMongoConverter.setCustomConversions(customConversions());
        return mappingMongoConverter;
    }

    @Bean
    public MongoCustomConversions customConversions() {
        return MongoCustomConversions.create(i -> {
            i.registerConverter(new BigDecimalToDecimal128Converter());
            i.registerConverter(new Decimal128ToBigDecimalConverter());
        });
    }
}
